package com.dayuanit.mall.bank.notify;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.dayuanit.mall.bank.dao.SinaOrderDao;
import com.dayuanit.mall.bank.domain.SinaNotifyResponse;
import com.dayuanit.mall.bank.domain.SinaOrder;
import com.dayuanit.mall.bank.dto.SinaPayResponse;
import com.dayuanit.mall.bank.exception.MallBusException;
import com.dayuanit.mall.bank.payenum.NotifyStatusEnum;
import com.dayuanit.mall.bank.util.DateUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component("sinaNotify")
public class SinaNotify {
	
	private static final Logger log = LoggerFactory.getLogger(SinaNotify.class);
	
	@Autowired
	private SinaOrderDao sinaOrderDao;
	
	@Value("#{configProperties['dayuanit.key']}")
	private String key;
	
	public SinaNotifyResponse sendNotify(SinaOrder so) {
		log.info("订单{}正在通知商户,地址：{}", so.getOrderId(), so.getSynchMerchantUrl());
		sinaOrderDao.updateNotifyTimes(so.getId());
		
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(so.getSynchMerchantUrl());
		
		SinaPayResponse sr = SinaPayResponse.instance()
						.setDealId(String.valueOf(so.getId()))
						.setDealTime(DateUtil.dateToString(so.getModifyTime(), DateUtil.PATTERN_YYYYMMDDHHMMSS))
						.setFee(so.getFee())
						.setMerchantAcctId(so.getMerchantId())
						.setOrderAmount(so.getOrderAmount())
						.setOrderId(so.getOrderId())
						.setOrderTime(DateUtil.dateToString(so.getOrderTime(), DateUtil.PATTERN_YYYYMMDDHHMMSS))
						.setPayAmount(so.getPayAmount())
						.setPayResult("10");
		
		String origin = sr.createOrigin(key);
		String sign = MD5(origin);
		sr.setSignMsg(sign);
		
		ObjectMapper objectMapper = new ObjectMapper();
		String notifyMsg = null;
		SinaNotifyResponse snr = new SinaNotifyResponse();
		try {
			notifyMsg = objectMapper.writeValueAsString(sr);
			List <NameValuePair> nvps = new ArrayList <NameValuePair>();
			nvps.add(new BasicNameValuePair("data", notifyMsg));
			httpPost.setEntity(new UrlEncodedFormEntity(nvps));
			
			CloseableHttpResponse response = httpclient.execute(httpPost);
		    HttpEntity entity = (HttpEntity)response.getEntity();
		    
		    //<result>1</result><redirecturl><![CDATA[http://www.yoursite.com/show.asp]]></redirecturl>
		    //{"result" : 1, redirecturl : "http://pay.dayuanit.xxxx"}
		    String msg = EntityUtils.toString(entity);
		    
		    log.info("商户返回信息：{}", msg);
		    if (StringUtils.isBlank(msg)) {
		    	throw new MallBusException("异步通知返回结果为空");
		    }
		    
		    snr = objectMapper.readValue(msg, SinaNotifyResponse.class);
		    if (!snr.processSuccess()) {
		    	throw new MallBusException("异步通知商户未正确处理");
		    }
		    
		} catch (MallBusException me) {
			log.error(me.getMessage());
		} catch (Exception e) {
			log.error("发送异步通知异常{}", e.getMessage(), e);
			throw new MallBusException("发送异步通知异常");
		}
		
		return snr;
	}
		
	private String MD5(String msg) {
		return DigestUtils.md5Hex(msg);
	}

}
